<?php
namespace Components\Trade\Second\Buy;

class Logic {
	private function getPaginate($builder, $limit, $page) {
		return ['code' => 0, 'pager'=>(new \Phalcon\Paginator\Adapter\QueryBuilder([
			'builder' => $builder,
			'limit' => $limit,
			'page' => $page
		])) -> getPaginate()];
	}

	private function makeBuilder() {
		return (new \Phalcon\Mvc\Model\Query\Builder())
			-> from([
				'tb' => __NAMESPACE__ . '\\Model',
				'fu' => 'Components\Account\User\\Model'
			])
			-> columns(
				'tb.trade_buy_id,tb.trade_sell_id,tb.from_user_id,tb.to_user_id,tb.profit,tb.amount,tb.original_amount,tb.tb.loop_number,tb.create_time,tb.last_time,tb.status,tb.image,' .
				'fu.account'
			)
			-> where('tb.from_user_id = fu.user_id')
			-> orderBy('tb.status ASC, tb.create_time ASC');
	}

	public function pager($parameters = [], $limit = 10, $page = 1) {
		return $this -> getPaginate($this -> makeBuilder(), $limit, $page);
	}

	public function match($parameters = [], $limit = 10, $page = 1) {
		$builder = $this -> makeBuilder() -> andWhere('tb.status = 0 AND tb.amount <= ' . $parameters['trade_sell'] -> amount . ' AND tb.from_user_id != ' . $parameters['trade_sell'] -> from_user_id);

		return $this -> getPaginate($builder, $limit, $page);
	}
}
